import 'dart:convert';

import 'package:boss/main.dart';
import 'package:boss/textStyle/text_style.dart';
import 'package:boss/ui/page/member/page/rechargeEdit.dart';
import 'package:boss/ui/widget/button/fixed_bottom_btn.dart';
import 'package:boss/ui/widget/center_title_app_bar.dart';
import 'package:boss/ui/widget/loading/loading.dart';
import 'package:common_utils/common_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:router/annotation.dart';
import 'package:hi_common/hi_common.dart';

@RouterConfig(RechargeRule.pageName)
class RechargeRule extends StatefulWidget {
  static const pageName = '/rechargeRulePage';

  @override
  MyRechargeRule createState() => MyRechargeRule('充值/消费规则');
}

class MyRechargeRule extends BaseState<RechargeRule> {
  List<dynamic> consumptionRuleArr = [];

  //接受
  dynamic dataAccept;

  MyRechargeRule(String pageName) : super(pageName);

  @override
  void initState() {
    super.initState();
    Future.delayed(Duration(milliseconds: 0)).then((e) {
      obtainQueryMemberRule();
    });
  }

  @override
  void didChangeDependencies() {}

  @override
  void dispose() {
    super.dispose();
  }

  //获取充值消费规则list
  obtainQueryMemberRule() async {
    try {
      showLoadingToast();
      var res = await api.queryMemberRule();

      if (res.successful()) {
        consumptionRuleArr = (res.data == null ? [] : (json.decode(res.data["rechargeAward"]) == null ? [] : json.decode(res.data["rechargeAward"])));
        dataAccept = (res.data);
//      print(json.decode(dataAccept["resumeAward"])["resumeAmount"]);

        setState(() {});
      } else {
        toast(res.msg);
      }
    } catch (e) {} finally {
      hideLoadingToast();
    }
  }

  //文本表头
  textHeader() {
    return Container(
      width: double.infinity,
      color: Colors.white,
      padding: EdgeInsets.only(
        left: 28.w,
        right: 28.w,
      ),
      child: dataAccept != null
          ? Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                SizedBox(
                  height: 20.w,
                ),
                if (dataAccept != null && dataAccept["resumeAward"] != null)
                  Text(
                    "${(json.decode(dataAccept["resumeAward"])["resumeAmount"] == null ? '' : ('每消费' + ((MoneyUtil.changeF2Y(json.decode(dataAccept["resumeAward"])["resumeAmount"] ?? 0)).toString()) + '元,赠送' + ((json.decode(dataAccept["resumeAward"])["giveScore"]) ?? 0).toString() + '积分;'))}",
                    style: TextStyleConstant().shallow_gray_28,
                  ),
                if (dataAccept != null && dataAccept["resumeAward"] != null)
                  Text(
                    "${(json.decode(dataAccept["resumeAward"])["openCardScore"] == null ? '' : ('开卡赠送' + ((json.decode(dataAccept["resumeAward"])["openCardScore"]).toString()) + '积分;'))}",
                    style: TextStyleConstant().shallow_gray_28,
                  ),
                if (dataAccept != null && dataAccept["scoreToCash"] != null)
                  Text(
                    parseScore(dataAccept),
                    style: TextStyleConstant().shallow_gray_28,
                  ),
                SizedBox(
                  height: 16.w,
                ),
              ],
            )
          : Container(),
    );
  }

  String parseScore(dataAccept) {
    try {
      return "${(json.decode(dataAccept["scoreToCash"])["score"] == null ? '' : (json.decode(dataAccept["scoreToCash"])["score"] == 0 ? '' : (json.decode(dataAccept["scoreToCash"])["score"]).toString() + '积分抵扣现金一元;'))}${dataAccept == null ? '' : (json.decode(dataAccept["scoreToCash"])["scoreTOCashMax"] == null ? '' : (json.decode(dataAccept["scoreToCash"])["scoreTOCashMax"] == 0 ? '' : ('积分抵扣不超过订单金额' + (json.decode(dataAccept["scoreToCash"])["scoreTOCashMax"]).toString() + '%;')))}";
    } catch (e) {
      return '0';
    }
  }

  contentList() {
    return Expanded(
      child: SingleChildScrollView(
        child: Container(
          child: Column(
            children: <Widget>[
              textHeader(),
              consumptionRuleArr.length == 0
                  ? Container(
                      margin: EdgeInsets.only(
                        top: 200.w,
                      ),
                      child: Text(
                        "暂无充值奖励规则",
                        style: TextStyleConstant().gray_28_deep,
                      ),
                    )
                  : Container(),
              Container(
                child: Column(
                  children: consumptionRuleArr
                      .asMap()
                      .keys
                      .map((item) => Container(
                            child: Container(
                              padding: EdgeInsets.only(
                                left: 28.w,
                                right: 28.w,
                              ),
                              width: double.infinity,
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.start,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: <Widget>[
                                  Padding(
                                    padding: EdgeInsets.only(
                                      top: 26.w,
                                      bottom: 26.w,
                                    ),
                                    child: Text(
                                      "规则${item + 1}",
                                      style: TextStyleConstant().normal_1_36,
                                    ),
                                  ),
                                  Text(
                                    "• 单次充值达${consumptionRuleArr[item]["rechargeAmount"] == null ? 0 : (MoneyUtil.changeF2Y(consumptionRuleArr[item]["rechargeAmount"]).toString())}元，赠送${consumptionRuleArr[item]["giveAmount"] == null ? 0 : (MoneyUtil.changeF2Y(consumptionRuleArr[item]["giveAmount"] ?? 0).toString())}元，赠送${consumptionRuleArr[item]["giveScore"] == null ? 0 : consumptionRuleArr[item]["giveScore"]}积分；",
                                    style: TextStyleConstant().normal_1_26,
                                  ),
                                ],
                              ),
                            ),
                          ))
                      .toList(),
                ),
              ),
              SizedBox(
                height: 60.w,
              )
            ],
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CenterTitleAppBar(
        title: '充值/消费规则',
        actions: <Widget>[],
      ),
      body: Container(
        child: Column(
          children: <Widget>[
            contentList(),
            FixedBottomBtn(
              title: "编辑规则",
              onTap: () async {
                Future.delayed(Duration(milliseconds: 300), () async {
                  var result = await Navigator.pushNamed(context, RechargeEdit.pageName, arguments: {
                    'data': dataAccept,
                  });
//                final result = await Navigator.push(context,MaterialPageRoute(builder: (context) => RechargeEdit()));

                  if (result != null) {
                    obtainQueryMemberRule();
                  }
                });
              },
              isShowShadow: false,
            ),
          ],
        ),
      ),
    );
  }
}
